package com.datastructure.test.lengthofchildchar;

public class LengthOfChildChar {
    public static void main(String[] args) {

    }

    public String LCS1(String s1, String s2) {
        int maxLength = 0;
        int index = 0;
        for (int i = 0; i < s2.length(); i++) {
            for (int j = i + 1; j <= s2.length(); j++) {
                if (s1.contains(s2.substring(i, j))) {
                    if (maxLength < j - i) {
                        maxLength = j - i;
                        index = i;
                    }
                } else break;
            }
        }
        if (maxLength == 0) { //没有相同的字符串
            return "-1";
        }
        return s2.substring(index, index + maxLength);
    }

    public String LCS2(String str1, String str2) {
        // write code here
        if (str1 == null || str2 == null || str1.equals(" ") || str2.equals(" ")) {
            return "-1";
        }
        //动态规划  二维数组，斜下来就是最长字串
        int str1len = str1.length();
        int str2len = str2.length();
        int maxLen = 0;
        int index = 0;
//        定义一个二维数组
        int[][] dp = new int[str1len][str2len];
        //第一步：划分
        for (int i = 0; i < str1len; i++) {
            for (int j = 0; j < str2len; j++) {
                if (str1.charAt(i) == str2.charAt(j)) {
                    if (j * i == 0) {
                        dp[i][j] = 1;
//                        if (maxLen == 0) {
//                            maxLen = 1;
//                            index = i;
//                        }
                    } else {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                        if (maxLen <= dp[i][j]) {
                            maxLen = dp[i][j];
                            index = i;
                        }
                    }
                }
            }
        }
        if (maxLen == 0) {
            return "-1";
        }
        return str1.substring(index - maxLen + 1, index + 1);
    }

}
